import { deleteBills, newBillFormData, queryBills, queryBillSettings, queryOrderList, updateBills } from '../service/bill'
import CustomSpreadsheet from './CustomSpreadsheet/index'
import { Spin, Button, Space, Input } from 'ant-design-vue'
import './XSpreadSheet.less'
import moment from 'moment'

import { addIcon, saveIcon } from './icons'
import MaterialsSelector from './MaterialsSelector'
import OrderPopup from './CustomSpreadsheet/OrderPopup'

const XSpreadSheet = {
  name: 'XSpreadSheet',
  data () {
    return {
      editable: false,
      materials: [],
      customers: [],
      formData: {
        dateSelect: 'all',
        datePicker: undefined
      },
      loading: false,
      changedCellRangeSet: new Set(),
      xs: null,
      visible: false
    }
  },
  mounted () {
    this.fetchData()
    this.createXS([], {
      editable: this.editable
    })
  },
  computed: {
    range () {
      var newValue = this.formData
      var today = moment()
      var nextStr = moment().add(100, 'year').format('YYYY-MM-DD')
      if (newValue.dateSelect === 'all') {
        return []
      }
      if (newValue.dateSelect === 'future') {
        var todayStr = today.format('YYYY-MM-DD')
        return [nextStr, todayStr]
      }
      if (newValue.dateSelect === 'year') {
        var lastYear = today.subtract(1, 'year').format('YYYY-MM-DD')
        return [nextStr, lastYear]
      }
      if (newValue.dateSelect === 'month') {
        var lastMonth = today.subtract(1, 'month').format('YYYY-MM-01')
        return [nextStr, lastMonth]
      }
      if (newValue.dateSelect === 'quarter') {
        var lastQuarter = today.subtract(3, 'month').format('YYYY-MM-DD')
        return [nextStr, lastQuarter]
      }
      if (newValue.dateSelect === 'week') {
        var lastDay = today.subtract(7, 'day').format('YYYY-MM-DD')
        return [nextStr, lastDay]
      }
      if (newValue.dateSelect === 'custom') {
        if (newValue.datePicker) {
          return [
            newValue.datePicker[1].format('YYYY-MM-DD'),
            newValue.datePicker[0].format('YYYY-MM-DD')
          ]
        }
      }
      return []
    }
  },
  methods: {
    async onCustomerCellClick (evt, cellKey, item) {
      const { offsetX, offsetY } = evt
      const cellRect = this.xs.data.getCellRectByXY(offsetX, offsetY)
      const offset = this.xs.sheet.getTableOffset()
      console.log(offset)
      const {
        left, top, width
      } = cellRect
      var position = {}
      if (top > (window.innerHeight - 200)) {
        position.bottom = (window.innerHeight - (top + 40)) + 'px'
      } else {
        position.top = (top + 40) + 'px'
      }
      if (left > (window.innerWidth - 420)) {
        position.left = (left - 400) + 'px'
      } else {
        position.left = (left + width) + 'px'
      }
      if (cellKey === 'total_qty' || cellKey === 'lostqty') {
        var result = await queryOrderList(cellKey, item)
        if (result.data.dataList) {
          var orderPopup = this.$refs['order-popup']
          orderPopup.show(result.data.dataList, position)
        }
      }
    },
    async handleSaveClick (evt) {
      if (!(this.xs instanceof CustomSpreadsheet)) return
      console.log('新数据', this.xs.helper.getAllNewData())
      console.log('保存', this.xs.helper.data.filter((item) => item.changed))
      var data = this.xs.helper.data.filter((item) => item.changed)
      var deleteData = this.xs.helper.helper.deleteData || []
      const allNewData = this.xs.helper.getAllNewData()
      const newData = allNewData.filter((item) => {
        if (isNaN(item.quantity) || !item.date) return false
        if (item.quantity < 0) return false
        if (item.tc_oeb01 && item.tc_oeb02) {
          item.orderId = item.tc_oeb01 + ':' + item.tc_oeb02
          return true
        } else {
          return false
        }
      })

      const formData = {
        old_full_row: [],
        new_full_row: [],
        pk_rows: []
      }

      /// 进一步标记
      /// 1. 标记修改
      var updatedDatas = data.filter((item) => item._bak && !!item.quantity)
      updatedDatas.forEach((item) => {
        formData.old_full_row.push(item._bak)
        formData.new_full_row.push({
          ...item._bak,
          oid: item.id,
          cus: item.customer,
          itm: item.material,
          tc_oeb05: item.date,
          tc_oeb04: item.quantity,
          tc_oeb02: item.tc_oeb02,
          tc_oeb01: item.tc_oeb01
        })
      })
      /// 2. 标记删除 - 修改
      var deletedDatas = data.filter((item) => item._bak && !item.quantity)
      deletedDatas.concat(deleteData).forEach((item) => {
        formData.pk_rows.push({
          ...item._bak
        })
      })

      /// 3. 标记新增
      var newDatas = data.filter((item) => !item._bak)
      newDatas.concat(newData).forEach((item) => {
        formData.old_full_row.push({})
        formData.new_full_row.push(newBillFormData({
          oid: item.id,
          cus: item.customer,
          itm: item.material,
          tc_oeb05: item.date,
          tc_oeb04: item.quantity,
          tc_oeb02: item.tc_oeb02,
          tc_oeb01: item.tc_oeb01
        }))
      })

      if (formData.old_full_row.length !== 0) {
        const response = await updateBills(formData.old_full_row, formData.new_full_row)
        if (response.status === 200 && response.data) {
          this.$message.info(response.data.msg)
          if (!response.data.success) {
            return
          }
          newDatas.forEach((item) => {
            item._bak = newBillFormData({
              oid: item.id,
              cus: item.customer,
              itm: item.material,
              tc_oeb05: item.date,
              tc_oeb04: item.quantity,
              tc_oeb02: item.tc_oeb02,
              tc_oeb01: item.tc_oeb01
            })
          })
        } else {
          this.$message.info('操作失败')
          return
        }
      }

      if (formData.pk_rows.length !== 0) {
        const response = await deleteBills(formData.pk_rows)
        if (response.status === 200 && response.data) {
          this.$message.info(response.data.msg)
          if (!response.data.success) {
            return
          }
          deletedDatas.forEach((item) => {
            delete item._bak
          })
        } else {
          this.$message.info('删除失败')
          return
        }
      }

      data.forEach((item) => {
        item.changed = false
      })
      const secondaryData = this.xs.helper.data.concat(newData)
      this.changedCellRangeSet = new Set()
      this.saveBtn.classList.add('disabled')
      // this.xs.helper.clear()
      this.updateXS(secondaryData, {
        editable: this.editable
      })
    },
    createXS (secondaryData, options = {}) {
      var addBtn = document.createElement('div')
      addBtn.innerHTML = addIcon
      addBtn.classList.add('add-icon')

      var saveBtn = document.createElement('div')
      saveBtn.innerHTML = saveIcon
      saveBtn.classList.add('save-icon')
      saveBtn.classList.add('disabled')

      this.addBtn = addBtn
      this.saveBtn = saveBtn
      var that = this
      this.xs = new CustomSpreadsheet('#spreadsheet', {
        secondaryTableData: secondaryData,
        showToolbar: true,
        showBottomBar: false,
        freeze: 'C4',
        editable: options.editable,
        extendToolbar: {
          left: [
            {
              el: this.saveBtn,
              tip: '保存',
              async onClick (evt) {
                if (!that.xs.editable) {
                  that.$message.info('您没有权限保存，请联系管理员')
                  return
                }
                that.loading = true
                try {
                  await that.handleSaveClick()
                } catch (error) {
                  console.log(error)
                } finally {
                  that.loading = false
                }
              }
            }
          ]
        },
        style: {
          align: 'center'
        }
      })
      const handleChange = () => {
        var data = this.xs.helper.data.filter((item) => item.changed)
        const newData = this.xs.helper.getAllNewData()
        if (data.length > 0 || newData.length > 0) {
          this.saveBtn.classList.remove('disabled')
          if (this.xs.data.selector) {
            this.changedCellRangeSet.add(this.xs.data.selector.range)
          }
        }
      }
      this.xs.on('custom-clicked', (cell, ri, ci) => {
        console.log('custom-clicked', cell, ri, ci)
        this.visible = true
        this.rowIndex = ri
        this.columnIndex = ci
      })
      console.log(new Date().getTime())
      this.xs.reRender()
      console.log(new Date().getTime())
      this.xs.on('error', (error) => {
        this.$message.info(error)
      })
      this.xs.on('change', (evt) => {
        handleChange()
      })
      this.xs.on('custom-cell-selected', (context) => {
        console.log(context)
        if (context.isGroupCell && context.cell.popup) {
          this.onCustomerCellClick(event, context.cell.key, context.cell.item)
        }
      })
      this.xs.on('cells-edit', (evt) => {
        console.log(evt)
        handleChange()
      })
    },
    updateXS (secondaryData, options = {
      editable: false
    }) {
      this.xs.resetData({
        secondaryTableData: secondaryData,
        ...options
      })
      this.materials = []
      this.customers = []
    },
    async fetchData () {
      this.loading = true
      try {
        console.log('开始时间:', new Date())
        await this.queryBillSettings()
        await this.queryBills()
        console.log('结束时间:', new Date())
      } catch (error) {
        console.log(error)
        this.updateXS([], {
          editable: this.editable
        })
      } finally {
        this.loading = false
      }
    },
    async queryBillSettings () {
      var result = await queryBillSettings()
      var enableObj = {
        enable_on_add: false,
        enable_on_edit: false,
        enable_on_view: false
      }
      if (result.status === 200 && result.data) {
        var reportFunctions = result.data.dataList.js[0].report_functions
        Object.keys(reportFunctions).forEach((key) => {
          var obj = reportFunctions[key]
          if (obj.enabled === '1' && obj.predefine_function === '新增') {
            enableObj.enable_on_add = true
          }
          if (obj.enabled === '1' && obj.predefine_function === '修改') {
            enableObj.enable_on_edit = true
          }
        })
        if (enableObj.enable_on_add || enableObj.enable_on_edit) {
          this.editable = true
        }
      }
    },
    async queryBills () {
      var result = await queryBills({
        ...this.formData,
        range: this.range
      })
      if (result.status === 200 && result.data) {
        this.$message.info(result.data.msg)
      } else {
        this.$message.info('查询失败')
        return
      }

      var res = result.data
      if (res.dataList) {
        var secondaryData = []
        res.dataList.map((item) => {
          var id = item.oid
          var customer = item.cus
          var material = item.itm
          var tcOeb01 = item.tc_oeb01
          var tcOeb02 = item.tc_oeb02
          var quantity = item.tc_oeb04
          var date = item.tc_oeb05
          var orderId = item.tc_oeb01 + ':' + item.tc_oeb02
          secondaryData.push({
            'id': id,
            'orderId': orderId,
            'tc_oeb01': tcOeb01,
            'tc_oeb02': tcOeb02,
            'date': date,
            'quantity': quantity,
            'material': material,
            'customer': customer,
            'total_qty': item.total_qty,
            'itm_name': item.itm_name,
            'customer_name': item.customer_name,
            'current_stock': item.current_stock,
            'safe_stock': item.safe_stock,
            'demand_total': item.demand_total,
            'lostqty': item.lostqty,
            '_bak': { ...item }
          })
        })
        console.log('渲染结束时间', new Date())
        this.updateXS(secondaryData, {
          editable: this.editable
        })
        console.log('渲染结束时间2', new Date())
      }
    }
  },
  render () {
    return <div class="x-spread-sheet-wrap">
      <Spin spinning={this.loading}>
        <div ref="spreadsheet" id="spreadsheet"></div>
        <div class="query-form">
          <Space>
              <Input
                size="small"
                placeholder="请输入订单号"
                v-model={this.formData.oeb01}
                style={{ width: 140 }}
                onSearch={(value) => {
                  console.log(value)
                  this.queryData()
                }}
              />
              <Input
                size="small"
                placeholder="请输入物料编号"
                v-model={this.formData.itm}
                style={{ width: 140 }}
                onSearch={(value) => {
                  console.log(value)
                  this.queryData()
                }}
              />
              <Input
                size="small"
                placeholder="请输入物料名称"
                v-model={this.formData.itm_name}
                style={{ width: 140 }}
                onSearch={(value) => {
                  console.log(value)
                  this.queryData()
                }}
              />
              <Input
                size="small"
                placeholder="请输入客户编号"
                v-model={this.formData.cus}
                style={{ width: 140 }}
                onSearch={(value) => {
                  console.log(value)
                  this.queryData()
                }}
              />
              <Input
                size="small"
                placeholder="请输入客户名称"
                v-model={this.formData.customer_name}
                style={{ width: 140 }}
                onSearch={(value) => {
                  console.log(value)
                  this.queryData()
                }}
              />
            {/* <Select
              size="small"
              v-model={this.formData.dateSelect}
              options={
                [
                  { label: '从今开始', value: 'future' },
                  { label: '前一周以后', value: 'week' },
                  { label: '前一月以后', value: 'month' },
                  { label: '前一季度后', value: 'quarter' },
                  { label: '前一年以后', value: 'year' },
                  { label: '自定义', value: 'custom' }
                ]
              }
            />
            <RangePicker
              v-model={this.formData.datePicker}
              disabled={this.formData.dateSelect !== 'custom'}
              format="YYYY-MM-DD"
              separator="~"
              size="small"
            /> */}
            <Button
              size="small"
              onClick={() => {
                this.fetchData()
              }}
            >查询</Button>
          </Space>
        </div>
      </Spin>
      <MaterialsSelector
        visible={this.visible}
        onCancel={() => {
          this.visible = false
        }}
        onOk={(rows) => {
          this.visible = false
          this.xs.selectedRows(rows, this.rowIndex)
          console.log(rows)
        }}
      />
      <OrderPopup
        ref="order-popup"
      />
    </div>
  }
}

export default XSpreadSheet
